package cli

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	"gitee.com/dark.H/go-remote-repl/datas"
	"gitee.com/dark.H/go-remote-repl/lpc"
)

func RunDaemon() {
	logfile := filepath.Join(os.TempDir(), filepath.Base(os.Args[0])+".log")
	args := []string{}
	for _, a := range os.Args {
		if a != "-D" {
			args = append(args, a)
		}
	}
	args = append([]string{args[0], "apiserv"}, args[1:]...)
	fmt.Println(args)
	datas.Daemon(args, logfile)
}

func StartServerAll(startLocal, startOuter bool) {
	if startLocal {
		if startOuter {
			if !lpc.IfOuterStart() {
				go StartOuterAPIServer()
				// os.Exit(0)
			}
		}
		if lpc.IfLocalStart() {
			lpc.KillAPI()
			os.Exit(0)
		} else {
			ln, err := lpc.UnixListener()
			if err != nil {
				log.Fatal("unix start err:", err)
			}
			RunningAPIListener(ln)
			os.Exit(0)
		}
	} else if startOuter {
		if lpc.IfLocalStart() {
			c := lpc.SimpleClient(lpc.SOCK_FILE_PATH)
			datas.JsonSend(datas.Data{
				"Op": "outer",
			}, c)
			log.Println(datas.JsonRecv(c))
			c.Close()
			os.Exit(0)
		} else {
			log.Println("already start outer!")
		}
	}
}
